<template>
    <div class="profile-container fade-in">
        <div class="page-header">
            <div class="header-content">
                <div class="title-section">
                    <h2 class="page-title">
                        <el-icon class="title-icon">
                            <User />
                        </el-icon>
                        个人信息
                    </h2>
                    <p class="page-subtitle">管理您的个人资料和账户设置</p>
                </div>
            </div>
        </div>

        <div class="profile-content">
            <el-row :gutter="24">
                <el-col :xs="24" :lg="8">
                    <!-- 个人信息卡片 -->
                    <el-card class="profile-card" shadow="hover">
                        <div class="profile-header">
                            <div class="avatar-section">
                                <div class="avatar-container" @click="triggerFileInput">
                                    <el-avatar 
                                        :size="120" 
                                        :src="userStore.user?.avatar" 
                                        :icon="UserFilled"
                                        class="user-avatar"
                                    />
                                    <div class="avatar-overlay">
                                        <el-icon><Camera /></el-icon>
                                        <span>更换头像</span>
                                    </div>
                                    <input
                                        ref="fileInput"
                                        type="file"
                                        accept="image/*"
                                        style="display: none"
                                        @change="handleAvatarUpload"
                                    />
                                </div>
                                <div class="user-basic-info">
                                    <h3 class="username">{{ userStore.user?.username || '未登录' }}</h3>
                                    <p class="user-role">{{ userStore.user?.role || '游客' }}</p>
                                    <div class="user-stats">
                                        <div class="stat-item">
                                            <div class="stat-number">{{ userStats.entries }}</div>
                                            <div class="stat-label">报名记录</div>
                                        </div>
                                        <div class="stat-item">
                                            <div class="stat-number">{{ userStats.days }}</div>
                                            <div class="stat-label">注册天数</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-card>

                    <!-- 账户安全 -->
                    <el-card class="profile-card" shadow="hover">
                        <template #header>
                            <div class="card-header">
                                <div class="header-left">
                                    <el-icon class="header-icon"><Lock /></el-icon>
                                    <span class="header-title">账户安全</span>
                                </div>
                            </div>
                        </template>
                        <div class="security-items">
                            <div class="security-item">
                                <div class="security-info">
                                    <div class="security-title">登录密码</div>
                                    <div class="security-desc">建议定期更换密码</div>
                                </div>
                                <el-button type="primary" plain size="small" @click="changePassword">
                                    修改
                                </el-button>
                            </div>
                            <div class="security-item">
                                <div class="security-info">
                                    <div class="security-title">手机绑定</div>
                                    <div class="security-desc">{{ userForm.phone || '未绑定手机号' }}</div>
                                </div>
                                <el-button type="primary" plain size="small" @click="bindPhone">
                                    {{ userForm.phone ? '修改' : '绑定' }}
                                </el-button>
                            </div>
                            <div class="security-item">
                                <div class="security-info">
                                    <div class="security-title">邮箱绑定</div>
                                    <div class="security-desc">{{ userForm.email || '未绑定邮箱' }}</div>
                                </div>
                                <el-button type="primary" plain size="small" @click="bindEmail">
                                    {{ userForm.email ? '修改' : '绑定' }}
                                </el-button>
                            </div>
                        </div>
                    </el-card>
                </el-col>

                <el-col :xs="24" :lg="16">
                    <!-- 基本信息编辑 -->
                    <el-card class="profile-card" shadow="hover">
                        <template #header>
                            <div class="card-header">
                                <div class="header-left">
                                    <el-icon class="header-icon"><Edit /></el-icon>
                                    <span class="header-title">基本信息</span>
                                </div>
                                <div class="header-actions">
                                    <el-button @click="resetForm" plain>
                                        <el-icon><Refresh /></el-icon>
                                        重置
                                    </el-button>
                                    <el-button type="primary" @click="handleSubmit" :loading="saving">
                                        <el-icon><Check /></el-icon>
                                        保存修改
                                    </el-button>
                                </div>
                            </div>
                        </template>

                        <el-form 
                            ref="formRef"
                            :model="userForm"
                            :rules="rules"
                            label-width="100px"
                            class="profile-form"
                        >
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="昵称" prop="nickname">
                                        <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="真实姓名" prop="realName">
                                        <el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="手机号码" prop="phone">
                                        <el-input v-model="userForm.phone" placeholder="请输入手机号码" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="电子邮箱" prop="email">
                                        <el-input v-model="userForm.email" placeholder="请输入电子邮箱" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="性别" prop="gender">
                                        <el-select v-model="userForm.gender" placeholder="请选择性别" style="width: 100%">
                                            <el-option label="男" value="male" />
                                            <el-option label="女" value="female" />
                                            <el-option label="保密" value="secret" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="生日" prop="birthday">
                                        <el-date-picker 
                                            v-model="userForm.birthday" 
                                            type="date" 
                                            placeholder="选择生日"
                                            style="width: 100%" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-form-item label="个人简介" prop="bio">
                                <el-input
                                    v-model="userForm.bio"
                                    type="textarea"
                                    :rows="4"
                                    placeholder="请输入个人简介"
                                />
                            </el-form-item>
                            <el-form-item label="地址" prop="address">
                                <el-input v-model="userForm.address" placeholder="请输入详细地址" />
                            </el-form-item>
                        </el-form>
                    </el-card>

                    <!-- 最近活动 -->
                    <el-card class="profile-card" shadow="hover">
                        <template #header>
                            <div class="card-header">
                                <div class="header-left">
                                    <el-icon class="header-icon"><Clock /></el-icon>
                                    <span class="header-title">最近活动</span>
                                </div>
                            </div>
                        </template>
                        <div class="activity-list">
                            <div v-for="(activity, index) in recentActivities" :key="index" class="activity-item">
                                <div class="activity-icon">
                                    <el-icon><Document /></el-icon>
                                </div>
                                <div class="activity-content">
                                    <div class="activity-text">{{ activity.text }}</div>
                                    <div class="activity-time">{{ activity.time }}</div>
                                </div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

        <!-- 修改密码对话框 -->
        <el-dialog v-model="showPasswordDialog" title="修改密码" width="400px" class="password-dialog">
            <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
                <el-form-item label="当前密码" prop="currentPassword">
                    <el-input 
                        v-model="passwordForm.currentPassword" 
                        type="password" 
                        show-password
                        placeholder="请输入当前密码" />
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                    <el-input 
                        v-model="passwordForm.newPassword" 
                        type="password" 
                        show-password
                        placeholder="请输入新密码" />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input 
                        v-model="passwordForm.confirmPassword" 
                        type="password" 
                        show-password
                        placeholder="请再次输入新密码" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="showPasswordDialog = false">取消</el-button>
                    <el-button type="primary" @click="submitPasswordChange">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { useUserStore } from '../stores/user'
import { useRouter } from 'vue-router'
import { UserFilled, Upload, Camera, User, Lock, Edit, Check, Clock, Document, Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, onMounted } from 'vue'

const userStore = useUserStore()
const router = useRouter()
const fileInput = ref(null)
const formRef = ref(null)
const passwordFormRef = ref(null)
const saving = ref(false)
const showPasswordDialog = ref(false)

const userForm = reactive({
    nickname: '',
    realName: '',
    phone: '',
    email: '',
    gender: 'secret',
    birthday: '',
    bio: '',
    address: ''
})

const passwordForm = reactive({
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
})

const userStats = reactive({
    entries: 12,
    days: 45
})

const recentActivities = ref([
    { text: '修改了个人信息', time: '2小时前' },
    { text: '报名了篮球比赛', time: '1天前' },
    { text: '完成了足球比赛缴费', time: '3天前' },
    { text: '更新了头像', time: '1周前' }
])

const rules = {
    nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    email: [
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ]
}

const passwordRules = {
    currentPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' }
    ],
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 8, message: '密码长度至少8位', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== passwordForm.newPassword) {
                    callback(new Error('两次输入的密码不一致'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
}

onMounted(() => {
    if (userStore.user) {
        userForm.nickname = userStore.user.nickname || ''
        userForm.realName = userStore.user.realName || ''
        userForm.phone = userStore.user.phone || ''
        userForm.email = userStore.user.email || ''
        userForm.gender = userStore.user.gender || 'secret'
        userForm.birthday = userStore.user.birthday || ''
        userForm.bio = userStore.user.bio || ''
        userForm.address = userStore.user.address || ''
    }
})

const triggerFileInput = () => {
    if (fileInput.value) {
        fileInput.value.click()
    }
}

const handleSubmit = async () => {
    if (!formRef.value) return
    
    try {
        await formRef.value.validate()
        saving.value = true
        
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        userStore.updateUserInfo({
            nickname: userForm.nickname,
            realName: userForm.realName,
            phone: userForm.phone,
            email: userForm.email,
            gender: userForm.gender,
            birthday: userForm.birthday,
            bio: userForm.bio,
            address: userForm.address
        })
        ElMessage.success('个人信息更新成功')
    } catch (error) {
        console.error(error)
        ElMessage.error('请填写正确的信息')
    } finally {
        saving.value = false
    }
}

const changePassword = () => {
    showPasswordDialog.value = true
}

const submitPasswordChange = async () => {
    if (!passwordFormRef.value) return
    
    try {
        await passwordFormRef.value.validate()
        ElMessage.success('密码修改成功')
        showPasswordDialog.value = false
        
        // 重置表单
        passwordForm.currentPassword = ''
        passwordForm.newPassword = ''
        passwordForm.confirmPassword = ''
    } catch (error) {
        ElMessage.error('请填写正确的信息')
    }
}

const bindPhone = () => {
    ElMessage.info('手机绑定功能开发中...')
}

const bindEmail = () => {
    ElMessage.info('邮箱绑定功能开发中...')
}

// 添加头像上传预览功能
const handleAvatarUpload = (event) => {
    const file = event.target.files?.[0]
    if (!file) return

    if (!file.type.startsWith('image/')) {
        ElMessage.error('请上传图片文件')
        return
    }

    // 检查文件大小
    if (file.size > 5 * 1024 * 1024) {
        ElMessage.error('图片大小不能超过5MB')
        return
    }

    const reader = new FileReader()
    reader.onload = (e) => {
        const avatarUrl = e.target.result
        userStore.updateAvatar(avatarUrl)
        ElMessage.success('头像更新成功')
    }
    reader.readAsDataURL(file)
}

// 添加表单重置功能
const resetForm = () => {
    if (!formRef.value) return
    
    ElMessageBox.confirm(
        '确定要重置表单吗？所有未保存的修改将丢失。',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        formRef.value.resetFields()
        if (userStore.user) {
            userForm.nickname = userStore.user.nickname || ''
            userForm.realName = userStore.user.realName || ''
            userForm.phone = userStore.user.phone || ''
            userForm.email = userStore.user.email || ''
            userForm.gender = userStore.user.gender || 'secret'
            userForm.birthday = userStore.user.birthday || ''
            userForm.bio = userStore.user.bio || ''
            userForm.address = userStore.user.address || ''
        }
        ElMessage.success('表单已重置')
    })
}

// 添加退出登录功能
const handleLogout = () => {
    ElMessageBox.confirm(
        '确定要退出登录吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        userStore.logout()
        ElMessage.success('已退出登录')
        router.push('/login')
    })
}
</script>

<style scoped>
.profile-container {
    animation: fadeIn 0.5s ease-out;
}

.page-header {
    margin-bottom: var(--spacing-xl);
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: var(--spacing-lg);
}

.title-section {
    flex: 1;
}

.page-title {
    display: flex;
    align-items: center;
    gap: var(--spacing-md);
    margin: 0 0 var(--spacing-sm) 0;
    font-size: 1.75rem;
    font-weight: 700;
    color: var(--text-primary);
}

.title-icon {
    font-size: 1.5rem;
    color: var(--primary-color);
}

.page-subtitle {
    margin: 0;
    color: var(--text-secondary);
    font-size: 0.9rem;
}

.profile-content {
    margin-bottom: var(--spacing-xl);
}

.profile-card {
    border-radius: var(--radius-lg);
    margin-bottom: var(--spacing-lg);
    transition: all 0.3s ease;
}

.profile-card:hover {
    box-shadow: var(--shadow-lg);
}

.profile-header {
    padding: var(--spacing-lg);
}

.avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: var(--spacing-lg);
}

.avatar-container {
    position: relative;
    cursor: pointer;
    border-radius: 50%;
    overflow: hidden;
}

.user-avatar {
    border: 4px solid var(--border-color);
    transition: all 0.3s ease;
}

.avatar-container:hover .user-avatar {
    border-color: var(--primary-color);
    transform: scale(1.05);
}

.avatar-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
    border-radius: 50%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: all 0.3s ease;
    color: white;
}

.avatar-container:hover .avatar-overlay {
    opacity: 1;
}

.avatar-overlay .el-icon {
    font-size: 1.5rem;
    margin-bottom: var(--spacing-xs);
}

.user-basic-info {
    text-align: center;
}

.username {
    margin: 0 0 var(--spacing-sm) 0;
    font-size: 1.5rem;
    font-weight: 700;
    color: var(--text-primary);
}

.user-role {
    margin: 0 0 var(--spacing-lg) 0;
    color: var(--text-secondary);
    font-size: 0.9rem;
}

.user-stats {
    display: flex;
    gap: var(--spacing-xl);
}

.stat-item {
    text-align: center;
}

.stat-number {
    font-size: 1.5rem;
    font-weight: 700;
    color: var(--primary-color);
    line-height: 1;
}

.stat-label {
    font-size: 0.75rem;
    color: var(--text-secondary);
    margin-top: var(--spacing-xs);
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left {
    display: flex;
    align-items: center;
    gap: var(--spacing-sm);
}

.header-icon {
    font-size: 1.25rem;
    color: var(--primary-color);
}

.header-title {
    font-weight: 600;
    color: var(--text-primary);
}

.header-actions {
    display: flex;
    gap: var(--spacing-sm);
}

.security-items {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-md);
}

.security-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: var(--spacing-md);
    border-radius: var(--radius-md);
    border: 1px solid var(--border-color);
    transition: all 0.3s ease;
}

.security-item:hover {
    background: var(--background-light);
    border-color: var(--primary-color);
}

.security-info {
    flex: 1;
}

.security-title {
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: var(--spacing-xs);
}

.security-desc {
    font-size: 0.875rem;
    color: var(--text-secondary);
}

.profile-form {
    padding: var(--spacing-lg) 0;
}

.activity-list {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-md);
}

.activity-item {
    display: flex;
    align-items: center;
    gap: var(--spacing-md);
    padding: var(--spacing-md);
    border-radius: var(--radius-md);
    transition: all 0.3s ease;
}

.activity-item:hover {
    background: var(--background-light);
}

.activity-icon {
    width: 40px;
    height: 40px;
    background: linear-gradient(135deg, var(--primary-color), var(--primary-light));
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 1rem;
}

.activity-content {
    flex: 1;
}

.activity-text {
    font-size: 0.875rem;
    color: var(--text-primary);
    margin-bottom: var(--spacing-xs);
}

.activity-time {
    font-size: 0.75rem;
    color: var(--text-secondary);
}

.password-dialog {
    border-radius: var(--radius-xl);
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: var(--spacing-md);
}

/* 响应式设计 */
@media (max-width: 768px) {
    .header-content {
        flex-direction: column;
        align-items: stretch;
        gap: var(--spacing-md);
    }
    
    .page-title {
        font-size: 1.5rem;
    }
    
    .user-stats {
        gap: var(--spacing-lg);
    }
    
    .card-header {
        flex-direction: column;
        align-items: stretch;
        gap: var(--spacing-sm);
    }
    
    .security-item {
        flex-direction: column;
        align-items: stretch;
        gap: var(--spacing-sm);
    }
}

@media (max-width: 480px) {
    .page-title {
        font-size: 1.25rem;
    }
    
    .user-avatar {
        width: 80px !important;
        height: 80px !important;
    }
    
    .username {
        font-size: 1.25rem;
    }
    
    .user-stats {
        flex-direction: column;
        gap: var(--spacing-md);
    }
    
    .profile-form {
        padding: var(--spacing-md) 0;
    }
}
</style>
